﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using IceDog.EFCore.ContosoUniversity.Models;

namespace IceDog.EFCore.ContosoUniversity.Pages.Students
{
    public class DeleteModel : PageModel
    {
        private readonly IceDog.EFCore.ContosoUniversity.Data.SchoolContext _context;

        public DeleteModel(IceDog.EFCore.ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Student Student { get; set; }
        public string ErrorMessage { get; set; }
        //saveChangesError 指示学生对象删除失败后是否调用该方法。 
        //删除操作可能由于暂时性网络问题而失败。 云端更可能出现
        //暂时性网络错误。 通过 UI 调用“删除”页 OnGetAsync 时，
        //saveChangesError 为 false。 当 OnPostAsync 调用 OnGetAsync
        //（由于删除操作失败）时，saveChangesError 参数为 true。
        public async Task<IActionResult> OnGetAsync(int? id, bool? saveChangesError = false)
        {
            if (id == null)
            {
                return NotFound();
            }

            Student = await _context.Student.FindAsync(id);

            if (Student == null)
            {
                return NotFound();
            }
            if (saveChangesError.GetValueOrDefault())
            {
                ErrorMessage = "Delete failed. Try again";
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Student = await _context.Student.FindAsync(id);

            if (Student != null)
            {
                try
                {
                    _context.Student.Remove(Student);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException /* ex */)
                {
                    //Log the error (uncomment ex variable name and write a log.)
                    return RedirectToAction("./Delete",
                                         new { id, saveChangesError = true });
                }
            }
            return RedirectToPage("./Index");
        }
    }
}
 